#!/bin/bash

outputs_dir=outputs.`date +%Y%m%d%H%M`
mkdir ${outputs_dir}

setYMLScalar()
{
  file=$1
  scalar_name=$2
  scalar_val=$3
  sed "s|^\ *${scalar_name}\ *:\ *.*$|${scalar_name}: ${scalar_val}|" $file > ${outputs_dir}/tmp.yml
  mv ${outputs_dir}/tmp.yml $file
}

runSims() {
  name=$1
  mechFile=$2
  thermFile=$3
  sparseThresh=$4
  ignitionDelayTime=$5
  dodense=$6

  ignitionDelayTime=`echo ${ignitionDelayTime} | sed 's/[eE]/\\*10\\^/' | sed 's/+//'`
  simTime=$(echo "scale=20; ${ignitionDelayTime} * 2" | bc)


  initFuelMassFracs=`grep -v "^#" inputs/${name}_fracs.log | egrep -iv '^\<O2\>|^\<N2\>' | sed 's/$/,/'`
  initFuelMassFracs=`echo $initFuelMassFracs`  #strip newlines
  initOxidMassFracs=`grep -v "^#" inputs/${name}_fracs.log | egrep -i  '^\<O2\>|^\<N2\>' | sed 's/$/,/'`
  initOxidMassFracs=`echo $initOxidMassFracs`  #strip newlines

  infile=${outputs_dir}/${name}_input.yml
  cp inputs/base.yml $infile

  setYMLScalar $infile mechFile $mechFile
  setYMLScalar $infile thermFile $thermFile
  setYMLScalar $infile reactorTime $simTime
  setYMLScalar $infile precThresh $sparseThresh
  setYMLScalar $infile fuelComp "{ $initFuelMassFracs }"
  setYMLScalar $infile oxidizerComp "{ $initOxidMassFracs }"
  setYMLScalar $infile mechLogFile ${outputs_dir}/${name}.cklog
  setYMLScalar $infile outFile ${outputs_dir}/${name}_mr_run.log
  
  zerork_exe=@CMAKE_INSTALL_PREFIX@/bin/zerork_cfd_plugin_tester.x

  #Dense 
  if [ "x"$dodense == "xY" ]
  then
    echo "Running ${name} Dense"
    setYMLScalar $infile cuda off
    setYMLScalar $infile linearSolver DirectDenseDVD
    setYMLScalar $infile nReactors 32 
    setYMLScalar $infile nMatrixReactors 32 
    setYMLScalar $infile outFile ${outputs_dir}/${name}_mr_run_dense.log
    $zerork_exe $infile > ${outputs_dir}/log_${name}_dense
  fi

  #Sparse
  echo "Running ${name} Sparse"
  setYMLScalar $infile cuda off
  setYMLScalar $infile linearSolver IterativeSparse 
  setYMLScalar $infile nReactors 32 
  setYMLScalar $infile nMatrixReactors 32 
  setYMLScalar $infile outFile ${outputs_dir}/${name}_mr_run_sparse.log
  $zerork_exe $infile > ${outputs_dir}/log_${name}_sparse
  rm $infile
}


nm=h2
mf=@CMAKE_INSTALL_PREFIX@/share/zerork/mechanisms/hydrogen/h2_v1b_mech.txt
tf=@CMAKE_INSTALL_PREFIX@/share/zerork/mechanisms/hydrogen/h2_v1a_therm.txt
st=3.20e-5
idt=8.2565998e-07

runSims $nm $mf $tf $st $idt Y

nm=dme
mf=@CMAKE_INSTALL_PREFIX@/share/zerork/mechanisms/dme/dme_24_mech.txt
tf=@CMAKE_INSTALL_PREFIX@/share/zerork/mechanisms/dme/dme_24_therm.txt
st=6.40e-5
idt=1.1e-05

runSims $nm $mf $tf $st $idt Y

nm=nc7h16-skel
mf=@CMAKE_INSTALL_PREFIX@/share/zerork/mechanisms/n-heptane_reduced/heptanesymp159_mec.txt
tf=@CMAKE_INSTALL_PREFIX@/share/zerork/mechanisms/n-heptane_reduced/heptanesymp_therm.txt
st=1.28e-4
idt=1.35e-05

runSims $nm $mf $tf $st $idt N


